<template>
  <div :class="isSubPage ? '' : 'app-container'">
    <div class="btns">
      <el-button v-show="isReadOnly === false" type="primary" @click="doFileUpload"><i class="el-icon-upload"></i>上传/续传</el-button>
      <el-button v-show="isReadOnly === false" type="primary" @click="doRefresh"><i class="el-icon-refresh"></i>刷新</el-button>
    </div>
    <el-table class="tl-table" ref="mainTable" :height="isSubPage ? '300px' : tableHeight" resizable-key="tableHeight" :resizable-refs="tableResizeRefs" v-loading="loading" :data="datas" @selection-change="doSelectChange" @sort-change="doSortChange" @row-dblclick="doRowDbClick" @row-click="doRowClick" row-key="id" border fit :row-class-name="doChangeRowClassName">
      <el-table-column type="index" label="序号" width="55px" align="center"></el-table-column>
      <el-table-column prop="name" label="文件名" min-width="250px" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="filesize" label="文件大小" width="100px" align="center" :formatter="formatFileSize"></el-table-column>
      <el-table-column prop="type" label="文件类型" width="100px"></el-table-column>
      <el-table-column prop="uploadusername" label="上传人" width="100px" :show-overflow-tooltip="true"></el-table-column>
      <el-table-column prop="dispuploadstate" label="状态" width="100px"></el-table-column>
      <el-table-column prop="progress" label="进度" width="150px">
        <template slot-scope="scope">
          <el-progress :show-text="true" :percentage="scope.row.progress"></el-progress>
        </template>
      </el-table-column>
      <el-table-column prop="recordtime" label="上传日期" width="180px" align="center" sortable="custom" sort-by="recordtime"></el-table-column>
      <el-table-column label="操作" width="110px" align="center" v-slot="scope" fixed="right">
        <el-dropdown trigger="hover">
          <el-button type="text" icon="el-icon-s-operation" style="margin-left:10px">更多<i class="el-icon-arrow-down el-icon--right"></i></el-button>
          <el-dropdown-menu>
            <el-dropdown-item v-if="isReadOnly === false" icon="el-icon-edit" @click.native="openEditDialog('editForm', scope.row.id)">编辑</el-dropdown-item>
            <el-dropdown-item v-if="isReadOnly === false" icon="el-icon-delete" @click.native="doDelete(scope.row.id)">删除</el-dropdown-item>
            <el-dropdown-item icon="el-icon-video-play" @click.native="doPlay(scope.row.id)">播放</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-table-column>
    </el-table>
    <!-- 列表分页 -->
    <el-row class="pagebar" ref="pager">
      <el-pagination @size-change="doChangeSize" @current-change="doChangeIndex" :current-page="pageInfo.currentPage" :page-sizes="pageInfo.pageSizes" :total="pageInfo.totalCount" layout="total, sizes, prev, pager, next, jumper" background class="tl-table-pagination"> </el-pagination>
    </el-row>
    <el-dialog :visible.sync="playAudioVisible" v-dialogDrag width="800px" class="audio-dialog" :title="this.audioName" :close-on-click-modal="false" style="" @close="playClose('audio')" :modal="false" :modal-append-to-body="false" :append-to-body="true">
      <tl-play-audio ref="playAudioForm"></tl-play-audio>
    </el-dialog>
    <el-dialog :visible.sync="playVideoVisible" v-dialogDrag width="800px" title="播放" class="tl-dialog" :close-on-click-modal="false" style="" @close="playClose('video')" :modal="false" :modal-append-to-body="false" :append-to-body="true">
      <tl-play-video ref="playVideoForm"></tl-play-video>
    </el-dialog>
    <el-dialog :visible.sync="uploadVisible" v-dialogDrag width="950px" top="60px" title="上传" class="tl-dialog" :close-on-click-modal="false" @close="uploadCose()" @before-close="beforeCloseUpload" :modal="false" :modal-append-to-body="false" :append-to-body="true">
      <tl-upload-file ref="uploadForm" :sourceType="sourceType" :sourceId="sourceId" style="height:400px" :before-upload="beforeUpload" :accept="limitType" :upload-arguments="uploadArgumentsObj" :limit="limit" :on-exceed="fileLimitFn" :chunk-size="chunkSize" @success="success"> </tl-upload-file>
    </el-dialog>
    <!-- 编辑界面 -->
    <tl-edit ref="editForm" @refresh="doRefresh"></tl-edit>
  </div>
</template>
<script>
import axios from '@tapui/utils/request'
/** mixins */
import { mixin_list } from '@tapui/mixins/mixin_list'
/** 子组件 */
import tlPlayAudio from '../audioPlay/playAudioHls'
import tlPlayVideo from '../audioPlay/playVideoHls'
import tlUploadFile from './uploadFile'
import tlEdit from './edit'
import { putAction, getAction, postAction, deleteAction } from '@tapui/utils/http'
import { decryptDes } from '../../../utils/password'
const BLOCK_SIZE = 5 * 1024 * 1024 // 块大小
const MIN_BLOCK_SIZE = 0 // 最小块大小
// 文件类型
const fileType = {
  audio: 'audio',
  video: 'video'
}
const fileStatus = {
  wait: 'wait',
  md5: 'md5',
  uploading: 'uploading',
  uploadFinish: 'uploadFinish',
  merge: 'merge',
  password: 'password',
  splice: 'splice',
  error: 'error',
  finish: 'finish',
  delete: 'delete'
}
export default {
  name: 'fileManage',
  mixins: [mixin_list],
  components: { tlPlayVideo, tlPlayAudio, tlUploadFile, tlEdit },
  data: () => ({
    description: '文件管理-列表查询',
    urlPrefix: '/meet/fileManage/',
    url: {
      load: '/meet/fileManage/load',
      getBlobSrc: '/play/getBlobLocalSrc'
    },
    tableData: [],
    // mixin_list中reduceHeight的高度 + 自定义文件上传div的高度
    reduceHeight: 134 + 45,
    // 排序参数
    sorterInfo: {
      sidx: 'recordtime',
      sord: 'desc'
    },
    playAudioVisible: false,
    playVideoVisible: false,
    uploadVisible: false,
    audioName: '播放',
    chunkSize: 3 * 1024 * 1024,
    rowDbClickActionType: '',
    remindFlag: 0, // 加载数据时是否通知父组件
    isQueryOnCreated: false,
    loading: true
  }),
  props: {
    limitType: {
      type: String,
      default: '.mp3,.aac,.wav,.m4a'
    },
    // 文件个数
    limit: {
      type: Number,
      default: 10
    },
    isSubPage: {
      type: Boolean,
      default: false
    },
    // 是否只读
    isReadOnly: {
      type: Boolean,
      default: false
    },
    sourceType: {
      type: String,
      default: ''
    },
    sourceId: {
      type: [Number, String],
      default: ''
    }
  },
  created() {},
  watch: {
    sourceId(val) {
      if (val) {
        this.loadData({})
      }
    }
  },
  computed: {
    uploadType() {
      return this.uploadArguments.type
    },
    uploadArgumentsObj() {
      return { ...this.uploadArguments }
    }
  },
  methods: {
    /** 加载数据之前 */
    beforeLoadData() {
      if (this.isSubPage) {
        this.queryParam.qry_sourceid = this.sourceId
      }
      this.queryParam = {
        ...this.queryParam,
        qry_sourcetype: this.sourceType
      }
      return true
    },
    /** 进行文件上传 */
    doFileUpload() {
      this.uploadVisible = true
    },
    /** 上传前校验 */
    beforeUpload(file) {
      let isRight
      let fileType = this.getFileExt(file.name)
      for (let type of this.limitType.split(';')) {
        if (type.toLowerCase().indexOf(fileType.toLowerCase()) === -1) {
          isRight = false
          break
        }
      }
      if (isRight === false) {
        this.$tap.alert(`上传文件只能是 ${this.limitType}格式!`, 'warning')
        return false
      }
      if (!file.size) {
        setTimeout(() => {
          this.$notify({
            message: '不能上传大小为0的文件',
            type: 'warning',
            offset: 50
          })
        }, 500)
        return false
      }
      return true
    },
    /** 文件扩展名 */
    getFileExt(fileName) {
      let arr = fileName.split('.')
      if (arr.length === 0) {
        return ''
      } else {
        return arr[arr.length - 1].toString().toLowerCase()
      }
    },
    // 文件个数限制钩子
    fileLimitFn(files) {
      this.$message.warning(`最多支持选择${this.limit}个文件`)
    },
    // 清空文件，暂未使用
    clearFiles() {
      this.$refs.upload.clearFiles()
    },
    // 上传成功
    success() {
      this.remindFlag = 1
      this.loadData({})
    },
    /** 表格大小格式化 */
    formatFileSize(row, column, cellValue, index) {
      let size = row[column.property]
      var fileSize = 0
      var len
      if (size / 1024 > 1024) {
        len = size / 1024 / 1024
        fileSize = len.toFixed(2) + 'MB'
      } else if (size / 1024 / 1024 > 1024) {
        len = size / 1024 / 1024 / 1024
        fileSize = len.toFixed(2) + 'GB'
      } else {
        len = size / 1024
        fileSize = len.toFixed(2) + 'KB'
      }
      return fileSize
    },
    /** 播放（音频、视频） */
    doPlay(id) {
      if (typeof id === 'undefined') {
        this.$tap.alert('没有完成，无法播放', 'warning')
        return
      }
      return getAction(this.url.load, { id: id }).then(res => {
        if (res.success) {
          if (res.result.uploadstate === fileStatus.uploading) {
            this.$tap.alert('文件没有上传完成，请继续上传', 'warning')
            return
          }
          if (res.result.uploadstate !== fileStatus.finish) {
            this.$tap.alert('文件安全处理中', 'warning')
            return
          }
          if (res.result.name.length > 40) {
            this.audioName = '播放 ' + res.result.name.slice(0, 40) + "……"
          } else {
            this.audioName = '播放 ' + res.result.name
          }
          // 请求加密 blob http路径
          axios({
            url: this.url.getBlobSrc,
            method: 'post',
            data: { qry_location: res.result.location },
            responseType: 'blob'
          }).then(response => {
            let url = URL.createObjectURL(response)
            var playSrc = {}
            playSrc.sourceSrc = url
            playSrc.sourceType = 'application/x-mpegURL'
            if (res.result.type.toLowerCase() === 'mp4') {
              this.playVideoVisible = true
              this.$nextTick(() => {
                this.$refs.playVideoForm.playSource(playSrc)
              })
            } else {
              this.playAudioVisible = true
              this.$nextTick(() => {
                this.$refs.playAudioForm.playSource(playSrc)
              })
            }
          })
        } else {
          this.$tap.alert(res.message, 'warning')
        }
      })
    },
    /** src播放 */
    doSrcPlay(res) {
      var playSrc = {}
      playSrc.sourceSrc = process.env.BASE_API + '/play/audio/' + res.result.location
      playSrc.sourceType = 'application/x-mpegURL'
      if (res.result.type !== null && res.result.type.toLowerCase() === 'mp4') {
        this.playVideoVisible = true
        this.$nextTick(() => {
          this.$refs.playVideoForm.playSource(playSrc)
        })
      } else {
        this.playAudioVisible = true
        this.$nextTick(() => {
          this.$refs.playAudioForm.playSource(playSrc)
        })
      }
    },
    /** 关闭音频 */
    playClose(type) {
      if (type === fileType.audio) {
        this.$refs.playAudioForm.stopPlay()
      } else if (type === fileType.video) {
        this.$refs.playVideoForm.stopPlay()
      }
    },
    /** 上传关闭 */
    uploadCose() {
      this.loadData({})
      this.$refs.uploadForm.handlePause()
      this.$refs.uploadForm.clearFiles()
    },
    beforeCloseUpload() {
      if (this.$refs.uploadForm.status === 'uploading') {
        this.$tap
          .confirm('上传没有完成，确认关闭吗？')
          .then(_ => {
            this.uploadCose()
          })
          .catch(_ => {})
      }
    },
    // 对接人力系统
    afterLoadData() {
      if (this.remindFlag === 1) {
        this.remindFlag = 0
        this.$emit('remindSuccess', this.datas.length)
      }
    },
    afterDoDelete() {
      this.remindFlag = 1
    }
  }
}
</script>
<style>
.btns {
  margin-bottom: 10px;
}
.select-file-button {
  height: 36px;
}
.select-file-input {
  position: relative;
  top: -4px;
}
/* .tl-dialog .el-dialog .el-dialog__header {
  background-color: #000;
}
.tl-dialog .el-dialog .el-dialog__body {
  background-color: #000;
}
.video-js .vjs-control-bar {
  margin-bottom: 11px;
} */
</style>
